<template>
	<view>
		<!-- <view class="bm-view">
			<baidu-map :center="center" :zoom="zoom" @ready="handler" @dragend="dragendHandler" class="bm-view">
                <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>
  			</baidu-map>
			<image class="cover-image" src="@/static/images/location.png"></image>
		</view> -->
		<view class="margin-top">
			<uni-forms ref="valiForm" :rules="rules" :modelValue="formData">
				<view class="margin-bottom">
					<uni-forms-item required name="deptId" class="bg-white padding-tb">
						<template #label>
							<view class="flex align-center padding-lr required">
								<view class="text-black">组织单位</view>
							</view>
						</template>
						<view class="margin-right" @click="toggle">
							<view class="flex align-center justify-between">
								<view class="margin-right-xs text-gray" v-if="!formData.deptId">
									请选择
								</view>
								<template v-else>
									<view class="flex-wrap text-black">
										{{ formData.deptId.name }}
									</view>
								</template>
								<view>
									<uni-icons v-if="formData.deptId" class="content-clear-icon" type="clear" :size="24"
										color="#c0c4cc" @click.native.stop="formData.deptId = null"></uni-icons>
									<uni-icons type="right" size="20" color="#8799a3"></uni-icons>
								</view>
							</view>
						</view>
					</uni-forms-item>
				</view>

				<uni-forms-item required name="buildingName" class="bg-white padding-tb-sm solid-bottom">
					<template #label>
						<view class="flex align-center padding-lr required">
							<view class="text-black">建筑物名称</view>
						</view>
					</template>
					<view class="margin-right">
						<uni-easyinput style="font-size: 28upx;" placeholderStyle="font-size: 28upx;"
							:inputBorder="false" v-model="formData.buildingName" placeholder="请输入内容"></uni-easyinput>
					</view>
				</uni-forms-item>
				<uni-forms-item required name="buildingType" class="bg-white padding-tb-sm solid-bottom">
					<template #label>
						<view class="flex align-center padding-lr required">
							<view class="text-black">建筑物类型</view>
						</view>
					</template>
					<view class="">
						<dict-select-action-sheet ref="buildingTypeSelect" :type="BUILDING_TYPE"
							v-model="formData.buildingType"></dict-select-action-sheet>
					</view>
				</uni-forms-item>
				
				<uni-forms-item required name="keHuBianHao" class="bg-white padding-tb-sm solid-bottom">
					<template #label>
						<view class="flex align-center padding-lr required">
							<view class="text-black">客户编号</view>
						</view>
					</template>
					<view class="margin-right">
						<uni-easyinput style="font-size: 28upx;" placeholderStyle="font-size: 28upx;"
							:inputBorder="false" v-model="formData.keHuBianHao" placeholder="请输入客户编号"></uni-easyinput>
					</view>
				</uni-forms-item>
				<uni-forms-item required name="mapIdentification" class="bg-white padding-tb solid-bottom">
					<template #label>
						<view class="flex align-center padding-lr required">
							<view class="text-black">地图标识</view>
						</view>
					</template>
					<view class="flex justify-end align-center">
						<view v-if="formData.mapIdentification && formData.mapIdentification.area"
							class="text-cut text-black" style="width:400rpx">
							{{ formData.mapIdentification && formData.mapIdentification.area }}
						</view>
						<view v-else class="text-cut text-gray" style="width:400rpx">
							请选择定位
						</view>
						<view class="flex margin-right" @click="chooseLocation">
							<uni-icons type="location" size="21" color="#515151"></uni-icons>
							<view class="margin-left-xs">定位</view>
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item required name="address" class="bg-white padding-tb solid-bottom">
					<template #label>
						<view class="flex align-center padding-lr required">
							<view class="text-black" style="width: max-content;">详细地址</view>
						</view>
					</template>
					<view class="margin-right">
						<uni-easyinput style="font-size: 28upx;" placeholderStyle="font-size: 28upx;"
							:inputBorder="false" autoHeight type="textarea" v-model="formData.address"
							placeholder="请输入内容"></uni-easyinput>
					</view>
				</uni-forms-item>
			</uni-forms>
			<uni-forms ref="secondValiForm" :rules="rules" :modelValue="formData" label-position="top">
				<uni-forms-item v-for="(responderItem, index) in responderList" :key="index" :name="responderItem.name"
					:label-width="90">
					<template #label>
						<view class="flex align-center padding-sm"
							:class="responderItem.name == 'firstResponderDO' || responderItem.name == 'secondResponderDO' ? 'required' : ''">
							<view class="text-black" style="width: max-content;">{{ responderItem.label }}</view>
						</view>
					</template>
					<view class="flex justify-end bg-white padding">
						<select-action-sheet :ref="responderItem.name" v-model="formData[responderItem.name]"
							:addEvent="()=>addPolice(responderItem.name)" :api="thingResponderPage" title="选择接警人"
							placeholder="请选择接警人" searchPlaceholder="请输入接警人名称">
							<template #label="{ selectItems }">
								<view class="flex justify-between response padding-lr" v-if="selectItems.length">
									<view>{{ selectItems.map((selectItem) => selectItem.name).join(',') }}</view>
									<view>{{ selectItems.map((selectItem) => selectItem.phone).join(',') }}</view>
								</view>
							</template>
							<template #item="{ item }">
								<view class="">
									<view>
										<text class="text-xl text-bold margin-right-sm">{{ item.name }}</text>
										{{ item.phone }}
									</view>
									<view class="margin-top-xs text-gray">
										{{ item.deptName }}
									</view>
								</view>
							</template>
						</select-action-sheet>
					</view>
				</uni-forms-item>
			</uni-forms>
		</view>

		<view style="height: 142upx;"></view>
		<view class="padding bg-white fixed-bottom">
			<button type="primary" @click="submit">保存</button>
		</view>

		<view>
			<!-- 普通弹窗 -->
			<uni-popup ref="popup">
				<view class="bg-white padding-top bottom-popup">
					<scroll-view scroll-y="true" style="height: 800upx;">
						<view class="cu-bar search padding-tb-sm">
							<view class="search-form round padding-lr" style="background-color: #f1f1f1;height: 40px;">
								<input style="height: 40px;" @confirm="searchConfirm" :adjust-position="false"
									type="text" placeholder="请输入组织机构名称" confirm-type="search"></input>
								<uni-icons class="margin-left-xs" type="search" size="19"></uni-icons>
							</view>
						</view>
						<ly-tree ref="tree" :tree-data="treeData" :ready="ready" node-key="id" showRadio
							:props="{ label: 'name' }" :filterNodeMethod="filterNodeMethod"
							@radio-change="handleRadioChange">
						</ly-tree>
					</scroll-view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import {
		getBuilding,
		updateBuilding,
		createBuilding
	} from "@/api/building/index"
	import {
		thingResponderPage
	} from "@/api/police/index"
	import {
		DICT_TYPE
	} from "@/utils/dict";
	import {
		listSimpleDept
	} from "@/api/system/dept";
	import {
		treeDataTranslate
	} from "@/utils/common";
	import {
		ruoyiJsonp
	} from "@/utils/ruoyi";
	export default {
		data() {
			return {
				center: {
					lng: 0,
					lat: 0
				},
				zoom: 3,
				ready: false, // 这里用于自主控制loading加载状态，避免异步正在加载数据的空档显示“暂无数据”
				treeData: [],
				thingResponderPage: thingResponderPage,
				BUILDING_TYPE: DICT_TYPE.BUILDING_TYPE,
				formData: {},
				// 校验规则
				rules: {
					deptId: {
						rules: [{
							required: true,
							errorMessage: '组织单位不能为空'
						}]
					},
					mapIdentification: {
						rules: [{
							required: true,
							errorMessage: '地图标识不能为空'
						}]
					},
					buildingName: {
						rules: [{
							required: true,
							errorMessage: '建筑物名称不能为空'
						}]
					},
					keHuBianHao: {
						rules: [{
							required: true,
							errorMessage: '客户编号不能为空'
						}]
					},
					firstResponderDO: {
						rules: [{
							required: true,
							errorMessage: '一级接警人不能为空'
						}]
					},
					secondResponderDO: {
						rules: [{
							required: true,
							errorMessage: '二级接警人不能为空'
						}]
					}
				},
				responderList: [{
						label: '一级接警人',
						name: 'firstResponderDO'
					},
					{
						label: '二级接警人',
						name: 'secondResponderDO'
					},
					{
						label: '三级接警人',
						name: 'thirdResponderDO'
					},
					{
						label: '四级接警人',
						name: 'fourthResponderDO'
					}
				]
			}
		},
		onLoad(e) {
			// 模拟异步请求
			listSimpleDept().then(res => {
				this.treeData = treeDataTranslate(res.data)
				this.ready = true;
			})
			uni.setNavigationBarTitle({
				title: e.id ? '修改建筑物' : '新建建筑物'
			});
			if (e.id) {
				getBuilding(e.id).then(response => {
					this.formData = {
						...response.data,
						deptId: {
							id: response.data.deptId,
							name: response.data.deptName
						},
						mapIdentification: {
							areaCode: [response.data.province, response.data.city, response.data.area, response
								.data.street
							],
							area: `${response.data.provinceName || ''}/${response.data.cityName || ''}/${response.data.areaName || ''}/${response.data.streetName || ''}`
						}
					}
				})
			}
		},
		methods: {
			// 添加接警人
			addPolice(responderName) {
				uni.navigateTo({
					url: '/pages/mine/add-police/add-police?isAdd=1'
				})
				uni.$once('refresh-police-list', () => {
					this.$refs[responderName][0].reload()
				})
			},
			handler({
				BMap,
				map
			}) {
				console.log(BMap, map)
				this.center.lng = 116.404
				this.center.lat = 39.915
				this.zoom = 15
			},
			dragendHandler(e) {
				console.log('%c [ e.target.getCenter() ]-242', 'font-size:13px; background:#400f4b; color:#84538f;', e
					.target.getCenter())
			},
			handleRadioChange(obj) {
				this.$set(this.formData, 'deptId', {
					id: obj.data.id,
					name: obj.data.name
				})
			},
			// 设置定位
			setLocation(result) {
			    console.log('setLocation', result);
				const townCode = result?.addressComponent?.town_code || ''
				const area = [
					result?.addressComponent?.province,
					result?.addressComponent.city,
					result?.addressComponent?.district,
					result?.addressComponent?.town,
				]
				if (townCode) {
					const areaCode = [
						`${townCode.slice(0, 2)}0000`,
						`${townCode.slice(0, 4)}00`,
						`${townCode.slice(0, 6)}`,
						townCode,
					]
					this.$set(this.formData, 'mapIdentification', {
						area: area.join('/'),
						areaCode,
						coordinate: `${result.location.lng},${result.location.lat}`
					})
				}
				const address = area.join('') + (result.name || '')
				this.$set(this.formData, 'address', address)
			},
			chooseLocation() {
				const that = this //注意这个在真机情况下 this 不等于 this 所以这样就保险用that
				if (this.formData.coordinate !== undefined && this.formData.coordinate) {
					// 如果已有保存的坐标值
					const coords = this.formData.coordinate.split(',');
					const latitude = parseFloat(coords[1]); // 纬度
					const longitude = parseFloat(coords[0]); // 经度
					// 百度坐标转高德坐标工具类（网上抄的）
					var bd_decrypt=(bd_lng, bd_lat)=>{
					      var X_PI = Math.PI * 3000.0 / 180.0
					      var x = bd_lng - 0.0065
					      var y = bd_lat - 0.006
					      var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI)
					      var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI)
					      var gg_lng = z * Math.cos(theta)
					      var gg_lat = z * Math.sin(theta)
					      return { lng: gg_lng, lat: gg_lat }
					}
					// 转换为高德坐标
					const arr = bd_decrypt(longitude, latitude)
					console.log('OVER-',arr);
					console.log(this.formData.coordinate, 'this.formData.coordinate')
					
				  setTimeout(() => {
					 uni.chooseLocation({
					 					latitude: arr.lat, //这里是模糊查询了坐标，并不准确，主要是让用户打开gps
					 					longitude: arr.lng,
					 					success: (res) => {
					 						console.log('哇哈哈哈或');
					 						console.log(res, 'res');
					 						//#ifdef H5
					 						that.setLocation({
					 							...result,
					 							name: `${res.address}${res.name}`
					 						})
					 						ruoyiJsonp(
					 							`https://api.map.baidu.com/geoconv/v1/?coords=${res.longitude},${res.latitude}&from=3&to=5&ak=a0kOCgbor5XRDKEQf85WGNy1Qf8T2Jg9`,
					 							(data) => {
					 								const location = data.result[0]
					 								ruoyiJsonp(
					 									`https://api.map.baidu.com/reverse_geocoding/v3/?ak=a0kOCgbor5XRDKEQf85WGNy1Qf8T2Jg9&output=json&coordtype=bd09ll&location=${location.y},${location.x}`,
					 									({
					 										result
					 									}) => {
					 										that.setLocation({
					 											...result,
					 											name: `${res.address}${res.name}`
					 										})
					 									}, "BaiduMap")
					 							}, "BaiduMapGeoconv")
					 						//#endif
					 						// #ifdef APP-PLUS
					 						uni.request({
					 							url: `https://api.map.baidu.com/geoconv/v1/?coords=${res.longitude},${res.latitude}&from=3&to=5&ak=a0kOCgbor5XRDKEQf85WGNy1Qf8T2Jg9`,
					 							success: ({
					 								data
					 							}) => {
					 								const location = data.result[0]
					 								uni.request({
					 									url: `https://api.map.baidu.com/reverse_geocoding/v3/?ak=a0kOCgbor5XRDKEQf85WGNy1Qf8T2Jg9&output=json&coordtype=bd09ll&location=${location.y},${location.x}`,
					 									success: (
					 										reverseGeocodingRes
					 										) => {
					 										that.setLocation({
					 											...
					 											reverseGeocodingRes
					 											.data
					 											.result,
					 											name: `${res.address}${res.name}`
					 										})
					 									}
					 								});
					 							}
					 						});
					 						// #endif
					 					}
					 }) 
				  },0)
				}else{
					uni.getLocation({
					type: 'gcj02',
					isHighAccuracy: true,
					success: function(res) {
						//注意，模拟器情况下的坐标可能是有问题的，所以你要真机测试，模拟器可以无视，但可以用模拟器走个流程而已。
						console.log('获取位置成功，GPS可能已开启');
						console.log('获取的坐标：',res);
						uni.chooseLocation({
							latitude: res.latitude, //这里是模糊查询了坐标，并不准确，主要是让用户打开gps
							longitude: res.longitude,
							success: (res) => {
								// console.log('哇哈哈哈或');
								// console.log(res, 'res');
								//#ifdef H5
								ruoyiJsonp(
									`https://api.map.baidu.com/geoconv/v1/?coords=${res.longitude},${res.latitude}&from=3&to=5&ak=a0kOCgbor5XRDKEQf85WGNy1Qf8T2Jg9`,
									(data) => {
										const location = data.result[0]
										ruoyiJsonp(
											`https://api.map.baidu.com/reverse_geocoding/v3/?ak=a0kOCgbor5XRDKEQf85WGNy1Qf8T2Jg9&output=json&coordtype=bd09ll&location=${location.y},${location.x}`,
											({
												result
											}) => {
												that.setLocation({
													...result,
													name: `${res.address}${res.name}`
												})
											}, "BaiduMap")
									}, "BaiduMapGeoconv")
								//#endif
								// #ifdef APP-PLUS
								uni.request({
									url: `https://api.map.baidu.com/geoconv/v1/?coords=${res.longitude},${res.latitude}&from=3&to=5&ak=a0kOCgbor5XRDKEQf85WGNy1Qf8T2Jg9`,
									success: ({
										data
									}) => {
										console.log('location',data);
										const location = data.result[0]
										uni.request({
											url: `https://api.map.baidu.com/reverse_geocoding/v3/?ak=a0kOCgbor5XRDKEQf85WGNy1Qf8T2Jg9&output=json&coordtype=bd09ll&location=${location.y},${location.x}`,
											success: (
												reverseGeocodingRes
												) => {
												console.log('reverseGeocodingRes',reverseGeocodingRes);
												that.setLocation({
													...
													reverseGeocodingRes
													.data
													.result,
													name: `${res.address}${res.name}`
												})
											}
										});
									}
								});
								// #endif
							}
						})
					},
					fail: function(err) {
						// #ifdef APP-PLUS
						// console.log('没有打开gps，牛逼了，强制让用户去打开，这里你可以不强制也行，你自己做决定');
						that.openGps() //这个在app情况下让手机打开gps的
						// #endif
					}
				});
				}
				
			},
			openGps() {
				//这个函数你只需要调用即可打开gps，下面已经判断好了是苹果还是安卓系统
				let system = uni.getSystemInfoSync(); // 获取系统信息
				if (system.platform === 'android') { // 判断平台
					var context = plus.android.importClass("android.content.Context");
					var locationManager = plus.android.importClass("android.location.LocationManager");
					var main = plus.android.runtimeMainActivity();
					var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
					if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
						uni.showModal({
							title: '提示',
							content: '请打开定位服务功能，否则功能无法正常使用',
							showCancel: false, // 不显示取消按钮
							success() {
								var Intent = plus.android.importClass('android.content.Intent');
								var Settings = plus.android.importClass('android.provider.Settings');
								var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
								main.startActivity(intent); // 打开系统设置GPS服务页面

							}
						});
					}
				} else if (system.platform === 'ios') {
					var cllocationManger = plus.ios.import("CLLocationManager");
					var enable = cllocationManger.locationServicesEnabled();
					var status = cllocationManger.authorizationStatus();
					plus.ios.deleteObject(cllocationManger);
					uni.showModal({
						title: '提示',
						content: '请打开定位服务功能，否则功能无法正常使用',
						showCancel: false, // 不显示取消按钮
						success() {
							var UIApplication = plus.ios.import("UIApplication");
							var application2 = UIApplication.sharedApplication();
							var NSURL2 = plus.ios.import("NSURL");
							var setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION");
							application2.openURL(setting2);
							plus.ios.deleteObject(setting2);
							plus.ios.deleteObject(NSURL2);
							plus.ios.deleteObject(application2);
						}
					});
				}
			},
			toggle() {
				this.$refs.popup.open('bottom')
				if (this.formData.deptId && this.formData.deptId.id) {
					this.$nextTick().then(() => {
						this.$refs.tree.setChecked(this.formData.deptId.id, true)
					})
				}
			},
			toggleClose() {
				this.$refs.popup.close()
			},
			filterNodeMethod(e, node) {
				return node.name.includes(e)
			},
			searchConfirm(e) {
				this.$refs.tree.filter(e.target.value)
			},
			submit() {
				// 在 onLoad 生命周期中，formData添加了一个 id 字段 ，此时这个字段是不参数校验的，所以结果中不返回
				// 在 validate(['id']) 方法中，指定第一个参数 ，即可返回id字段
				this.$refs.valiForm.validate(['id'], (err, formData) => {
					if (!err) {
						this.$refs.secondValiForm.validate().then(res => {
							const input = {
								...formData,
								deptId: formData.deptId.id,
								firstResponderId: res.firstResponderDO?.id || null,
								secondResponderId: res.secondResponderDO?.id || null,
								thirdResponderId: res.thirdResponderDO?.id || null,
								fourthResponderId: res.fourthResponderDO?.id || null,
								province: formData.mapIdentification.areaCode[0],
								city: formData.mapIdentification.areaCode[1],
								area: formData.mapIdentification.areaCode[2],
								street: formData.mapIdentification.areaCode[3],
								coordinate: formData.mapIdentification.coordinate,
							}
							console.log(input, 'input')
							delete input.mapIdentification
							uni.showLoading({
								title: input.id ? "更新中..." : "创建中...",
							})
							if (input.id) {
								console.log('%c [ input ]-363',
									'font-size:13px; background:#db1fcc; color:#ff63ff;', input)
								updateBuilding(input).then(res => {
									uni.$emit('buildingListReload', true)
									uni.navigateBack()
								}).finally(() => {
									uni.hideLoading()
								})
							} else {
								createBuilding(input).then(res => {
									uni.$emit('buildingListReload', true)
									uni.navigateBack()
								}).finally(() => {
									uni.hideLoading()
								})
							}
						})
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	.fixed-bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
	}

	.bm-view {
		width: 100%;
		height: 300px;
	}

	.cover-image {
		height: 68rpx;
		width: 68rpx;
		position: fixed;
		/* #ifdef APP-PLUS */
		position: absolute;
		/* #endif */
		top: 20%;
		left: 50%;
		margin-top: -30rpx;
		margin-left: -30rpx;
	}
</style>